package site.xuxingcan.contactchange;

import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.util.Log;

import java.util.ArrayList;
import java.util.Random;

/**
 * Created by xuxingcan on 2016/10/22.
 */
public class ContactUtil {
    public static void AddContact(Context context, String phone) throws Exception {
        Uri uri = Uri.parse("content://com.android.contacts/raw_contacts");
        ContentResolver resolver = context.getContentResolver();
        ArrayList<ContentProviderOperation> operations = new ArrayList<ContentProviderOperation>();
        ContentProviderOperation op1 = ContentProviderOperation.newInsert(uri)
                .withValue("account_name", null)
                .build();
        operations.add(op1);
        uri = Uri.parse("content://com.android.contacts/data");
        //添加姓名
        ContentProviderOperation op2 = ContentProviderOperation.newInsert(uri)
                .withValueBackReference("raw_contact_id", 0)
                .withValue("mimetype", "vnd.android.cursor.item/name")
                .withValue("data2", getString(3))
                .build();
        operations.add(op2);
        //添加电话号码
        ContentProviderOperation op3 = ContentProviderOperation.newInsert(uri)
                .withValueBackReference("raw_contact_id", 0)
                .withValue("mimetype", "vnd.android.cursor.item/phone_v2")
                .withValue("data1", phone)
                .withValue("data2", "2")
                .build();
        operations.add(op3);
        resolver.applyBatch("com.android.contacts", operations);
    }

    public static void DeleteAll(Context context) throws Exception {
        //根据姓名求id
        Uri uri1 = Uri.parse("content://com.android.contacts/raw_contacts");
        Uri uri2 = Uri.parse("content://com.android.contacts/data");
        ContentResolver resolver = context.getContentResolver();
        Cursor cursor = resolver.query(uri1, new String[]{"_id"}, null, null, null);
        ArrayList<String> ids = new ArrayList<>();
        while (cursor.moveToNext()) {
            ids.add(cursor.getString(cursor.getColumnIndex("_id")));
        }
        Log.i("xuxingcan", "ids.size() = " + ids.size());
        Log.i("xuxingcan", "cursor.getCount() = " + cursor.getCount());
        for (String id : ids) {
            resolver.delete(uri1, "_id=?", new String[]{id});
            resolver.delete(uri2, "raw_contact_id=?", new String[]{id});
        }
    }

    private final static int delta = 0x9fa5 - 0x4e00 + 1;

    public static String getString(int length) {
        StringBuffer buffer = new StringBuffer();
        Random ran = new Random();
        for (int i = 0; i < length; i++) {
            buffer.append((char) (0x4e00 + ran.nextInt(delta)));
        }
        return buffer.toString();
    }
}
